import React, { Component } from 'react'
import { UdTable, columnRenders } from '@/lib'

const UnderCustomerTb = function (props) {
  const { type } = props
  const expandedRowRender = (record, index, indent, expanded) => {
    if (!expanded) { // 不是展开直接return
      return
    }
    const columns:any = terminalColumns
    const data = record.items||[]
    return <UdTable rowKey='id' columns={columns} dataSource={data} pagination={false} />
  }

  let columns:any = [
    ['序号','id'],
    ['客户名称','companyName'],
    ['客户类型','agentType'],
    ['联系人姓名','contact'],
    ['联系人电话','phone'],
    ['地址','address'],
    {
      title: '操作',
      dataIndex: 'operate',
      render: columnRenders.operate([
        {title:'查看详情',show:(text,row)=>row.agentType,action:(text,row)=>toDetail(row)}
      ])
    }
  ]
  const terminalColumns = [
    ['序号','id'],
    ['客户名称','terminalName'],
    ['客户类型','agentType',()=><div>终端</div>],
    ['联系人姓名','contact'],
    ['联系人电话','phone'],
    ['地址','address'],
  ]
  if (type=='terminal') {
    columns = terminalColumns
  }
  const toDetail = (row) => {
    const { id,agentType='0',agentCode,belongAreaCode,brandCode,agentName } = row
    props.history.push('/customer/detail/'+id+'/'+agentType+'?agentCode='+agentCode+'&belongAreaCode='+belongAreaCode+'&brandCode='+brandCode+'&agentName='+agentName)
  }
  // const data = props.dataSource
  const data = deepLoopReplaceData(props.dataSource)
  const quering = props.loading
  const { onChange,pagination } = props
  return(
    <UdTable
      rowKey='id'
      columns={columns}
      dataSource={data}
      loading={quering}
      pagination={pagination}
      onChange={onChange}
      expandedRowRender={type!=='terminal'&&expandedRowRender}
    />
  )
}
export default UnderCustomerTb

// children默认会使table渲染成可展开树型table，这里需要替换children为其他字段名
function deepLoopReplaceData(datas,oldKey='children',key='items') {
  if (!Array.isArray(datas)||datas.length<1) {
    return datas
  }
  let res = []
  datas.map(data=>{
    const {[oldKey]:children,...reset} = data
    // 剔除oldKey数据
    let item = reset
    if (children) {
      // 使用新key替换oldKey的数据
      item[key] = deepLoopReplaceData(children)
    }
    res.push(item)
  })
  return res
}
